import React, {useContext, useEffect, useRef, useState} from 'react';
import PropTypes from 'prop-types';
import CarouselContext from './CarouselContext';
import styles from './style.module.scss';

const CarouselItem = (props) => {
    const targetContent = useRef({
		x: 0,
		y: 0,
		scale: 1,
		duration: 0
	});
	const [style, setStyle] = useState();
	const updateStyle = () => {
		const {x, y, scale, duration} = targetContent.current;
		setStyle({
			transform: `matrix(${scale}, 0, 0, ${scale}, ${x}, ${y})`,
			transitionDuration: `${duration}ms`
		});
	};
	const {pushItem, rootWidth} = useContext(CarouselContext);
	const move = (distX, distY) => {
		targetContent.current.x += distX;
		targetContent.current.y += distY;
		updateStyle();
	};
    const isToEdge = () => {
		if (targetContent.current.scale > 1) {
			return (
				targetContent.current.x >= 0 || targetContent.current.x <= -rootWidth
			);
		}
		return true;
	};
	const startPosition = (scale, x, y) => {
		/* if (!isToEdge()) {
			return;
		} */
		targetContent.current = {
			...targetContent.current,
			x,
			y,
			scale,
			duration: 0
		};
		updateStyle();
	};
	const endPosition = (x, y) => {
		targetContent.current = {
			...targetContent.current,
			x,
			y,
			duration: 300
		};
		updateStyle();
	};
	const zoom = (scale, x, y) => {
		targetContent.current = {
			...targetContent.current,
			x,
			y,
			scale,
			duration: 0
		};
		updateStyle();
	};
	useEffect(() => {
		const itemIndex = pushItem({
			move,
			isToEdge,
			startPosition,
			endPosition,
			zoom
		});
		targetContent.current.x = itemIndex * rootWidth;
		updateStyle();
	}, []);
	return (
		<div className={styles.carouselItem} style={style}>
			{props.children}
		</div>
	);
};

CarouselItem.propTypes = {
	children: PropTypes.any
};

export default CarouselItem;
